package StudyCode.summary.zipfile;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReadingFileOfObjectsSequentially {
	private static ObjectInputStream input;

	public static void main(String[] args) {
		openFile();
		readRecords();
		closeFile();
	}

	public static void openFile() {
		try {
			input = new ObjectInputStream(
					Files.newInputStream(Paths.get("clients.ser")));
		} catch (IOException ioException) {
			System.err.println("Error opening file.");
			System.exit(1);
		}
	}

	public static void readRecords() {
		System.out.printf("%-10s%-12s%-12s%10s%n", "Account", "First Name", "Last Name", "Balance");

		try {
			while (true) {
				Account record = (Account) input.readObject();

				System.out.printf("%-10d%-12s%-12s%10.2f%n",
						record.getAccount(), record.getFirstName(),
						record.getLastName(), record.getBalance());
			}
		} catch (EOFException endOfFileException) {
			System.out.printf("%nNo more records%n");
		} catch (ClassNotFoundException classNotFoundException) {
			System.err.println("Invalid object type. Terminating.");
		} catch (IOException ioException) {
			System.err.println("Error reading from file. Terminating.");
		}
	}

	public static void closeFile() {
		try {
			if (input != null)
				input.close();
		} catch (IOException ioException) {
			System.err.println("Error closing file. Terminating.");
			System.exit(1);
		}
	}
}


class Account implements java.io.Serializable {
	private int account;
	private String firstName;
	private String lastName;
	private double balance;

	// initializes an Account with default values
	public Account() {
		this(0, "", "", 0.0); // call other constructor
	}

	// initializes an Account with provided values
	public Account(int account, String firstName,
	               String lastName, double balance) {
		this.account = account;
		this.firstName = firstName;
		this.lastName = lastName;
		this.balance = balance;
	}

	// set account number
	public void setAccount(int acct) {
		this.account = account;
	}

	// get account number
	public int getAccount() {
		return account;
	}

	// set first name
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	// get first name
	public String getFirstName() {
		return firstName;
	}

	// set last name
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	// get last name
	public String getLastName() {
		return lastName;
	}

	// set balance
	public void setBalance(double balance) {
		this.balance = balance;
	}

	// get balance
	public double getBalance() {
		return balance;
	}
}
